<template>
	<view class="box">
		<navBar title="订单" backJudge></navBar>
		<view class="addressList">
			<view class="top">
				<view class="text">服务保障</view>
				<view class="tips">明码标价 | 未上门随时退 | 3天质保 ></view>
			</view>
			<view class="item" @click="toDetail">
				<view style="display: flex;align-items: center;">
					<uni-icons color="blue" type="map-pin-ellipse"></uni-icons>
					<view class="where">{{defaultAdd ? defaultAdd.city.mergerName : '未选择地址'}}</view>
				</view>
				<view style="display: flex;align-items: center;">
					<view class="detail">{{defaultAdd ? defaultAdd.detail : '未选择地址'}}</view>
					<uni-icons class="icon" type="right"></uni-icons>
				</view>
				<view style="display: flex;align-items: center;">
					<view class="name" v-if="defaultAdd">{{defaultAdd.userName}} {{defaultAdd.phone}}</view>
					<view class="name" v-else>未选择地址</view>
				</view>
			</view>
			<view class="time" @click="openTime()">
				<view class="title"><uni-icons type="calendar" color="blue"
						style="margin-right: 5px;"></uni-icons>选择上门时间</view>
				<view class="timeBox">
					<view class="value">{{dateValue}}</view>
					<uni-icons type="right"></uni-icons>
				</view>
			</view>
		</view>

		<view class="BodyBox">
			<view class="shopList" v-if="list.length > 0">
				<view class="item" v-for="(itemC,indexC) in list.filter(i=>i.cart.length != 0)" :key="indexC">
					<view class="title">{{itemC.name}}</view>
					<view class="cart" v-for="(item,index) in itemC.cart" :key="index">
						<view class="formation">
							<image v-if="car" :src="item.item.image" class="img" mode="aspectFill"></image>
							<image v-else :src="this.detail.image" class="img" mode="aspectFill"></image>
							<view class="form">
								<view>
									<view class="name">{{item.item.storeName}}</view>
									<view class="sku" style="margin-top: 20rpx;">规格:<span v-for="(attr,attrindex) in item.itemAttrValue" :key="attrindex">{{attr.attrValue}}</span></view>
								</view>
								<view class="priceBox">
									<view class="price"><span class="icon">￥</span>{{item.addingTimePrice}}</view>
									<view class="numBox">
										<view class="num">{{item.num}}</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>


			<view class="shopList" v-if="detail">
				<view class="item">
					<view class="title">{{detail.name}}</view>
					<view class="cart">
						<view class="formation">
							<image :src="this.detail.image" class="img" mode="aspectFill"></image>
							<view class="form">
								<view>
									<view class="name">{{detail.storeName}}</view>
									<view class="sku" style="margin-top: 10rpx;">规格:<span v-for="(item,index) in detail.attrValueList" :key="index">{{item.attrValue[0].attrValue}}</span></view>
								</view>
								<view class="priceBox">
									<view class="price"><span class="icon">￥</span>{{total || 0}}</view>
									<view class="numBox">
										<view class="num">1</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>


			<view class="content">
				<view class="title">备注</view>
				<input placeholder="备注你的需求" v-model="inputValue" :inputBorder="false"
					type="textarea"></input>
			</view>


			<view class="totalBox">
				<view @click="toCoupon" class="couponBox">
					<view class="text">优惠卷</view>
					<view class="coupon">{{coupon || '未使用'}}<uni-icons type="right"></uni-icons></view>
				</view>
			</view>
		</view>

		<view class="buttonBox">
			<view class="price" style="margin-top: -30rpx;"><span class="icon">￥</span>{{total}}</view>
			<view class="button" @click="buy" style="margin-top: -30rpx;">下单</view>
		</view>

		<uni-popup ref="timeWindow">
			<view class="window">
				<view class="title">你期望的上门服务时间</view>
				<view class="tips">师傅接单后电话与您确认最终上门时间</view>
				<view class="body">
					<scroll-view class="left" :scroll-y="true">
						<view @click="chooseDate(index,item)" :class="actDate.date === index?'act':''" class="item"
							v-for="(item,index) in dateBox" :key="index">{{item}}</view>
					</scroll-view>
					<scroll-view class="right" :scroll-y="true">
						<view class="tip" v-if="timeBox.length===0">今日暂无时间可选 上班时间8:00~18:00</view>
						<view v-else @click="chooseTime(index,item)" :class="actDate.time === index?'act':''"
							class="item" v-for="(item,index) in timeBox" :key="index">{{item}}</view>
					</scroll-view>
				</view>
				<view class="button" @click="submit">确定</view>
				<uni-icons class="icon" @click="close" type="closeempty"></uni-icons>
			</view>
		</uni-popup>

		<uni-popup ref="backWindow">
			<view class="backWindow">
				<view class="title">确定要返回了吗？</view>
				<view class="content">离支付成功只差了一步了</view>
				<view class="button" @click="backClose">取消</view>
				<view class="tips" @click="navBack">确定返回</view>
			</view>
		</uni-popup>
		
	</view>
</template>

<script>
	import navBar from '../../components/navbars/navbars.vue'
	import {address,createOrder,createPay,ShopCar,attrValuePrice,shopDetail} from '@/utils/API.js'
	export default {
		data() {
			return {
				dateValue: '',
				actDate: {
					date: 0,
					time: 0
				},
				coupon: '',
				addressList: [],
				defaultAdd: {},
				datetimerange: '',
				id: '',
				inputValue: '',
				list: [],
				total: 0,
				detail: '',
				attrId: '',
				dateBox: [],
				timeBox: [],
				nowTimeBox: [],
				attrList:[],
				car:false
			}
		},
		components:{
			navBar
		},
		onLoad(e) {
			console.log(e,'e');
			if(e.car){
				this.car = true
				this.total = e.money
				console.log('this.total',this.total);
			}
		
			console.log(1111111111111111111111111111111);
			if(e.attrList){
				this.attrList = JSON.parse(e.attrList)
				this.id = e.id
				this.attrId = e.attrId
			}
			this.generateDateArrayWithWeekday()
			this.generateTimeSlotsSimplified()
			this.getData()
			if (!this.id) {
				this.getShop()
			} else {
				this.getDetail()
			}
		},
		methods: {
			navBack(){
				uni.navigateBack()
			},
			backClose(){
				this.$refs.backWindow.close()
			},
			back(){
				this.$refs.backWindow.open('center')
			},
			close() {
				this.$refs.timeWindow.close()
			},
			submit() {
				if (this.timeBox.length === 0) {
					uni.showToast({
						title: '请选择时间',
						icon: 'none'
					})
					return
				}

				this.dateValue = this.dateBox[this.actDate.date] +' '+this.timeBox[this.actDate.time]
				this.$refs.timeWindow.close()
			},
			chooseTime(index, item) {
				this.actDate.time = index
			},
			chooseDate(index, item) {
				this.actDate.date = index
				this.actDate.time = 0
				if (index === 0) {
					this.timeBox = this.nowTimeBox
				} else {
					this.timeBox = ["08:00-09:00", "09:00-10:00", "10:00-11:00", "11:00-12:00", "12:00-13:00",
						"13:00-14:00", "14:00-15:00", "15:00-16:00", "16:00-17:00", "17:00-18:00"
					]
				}
			},
			generateDateArrayWithWeekday() {
				// 定义一个数组来映射星期几的数字到名称
				const weekdays = ['日', '一', '二', '三', '四', '五', '六'];

				// 获取今天的日期
				const today = new Date();
				const year = today.getFullYear();
				const month = today.getMonth() + 1; // 月份是从0开始的，所以需要加1
				const day = today.getDate();

				// 创建一个数组来存储日期字符串
				const dateArray = [];

				// 遍历今天及后6天的日期
				for (let i = 0; i <= 7; i++) {
					// 创建一个新的日期对象，设置为今天的日期加上i天
					const date = new Date(year, month - 1, day + i);

					// 获取星期几的数字，并从weekdays数组中获取对应的名称
					const weekday = weekdays[date.getDay()];

					// 获取月份和日期，并格式化为两位数
					const formattedMonth = String(date.getMonth() + 1).padStart(2, '0');
					const formattedDay = String(date.getDate()).padStart(2, '0');

					// 创建日期字符串，并添加到数组中
					const dateString = `周${weekday} ${formattedMonth}月${formattedDay}日`;
					dateArray.push(dateString);
				}

				this.dateBox = dateArray;
			},
			openTime() {
				this.$refs.timeWindow.open('bottom')
			},
			toCoupon() {
				uni.$once('coupon', (item) => {
					console.log(item);
				})
				uni.navigateTo({
					url: '/pages/user/coupon?type=choose&price=' + this.total
				})
			},
			async getData() {
				const res = await address()
				if(res.code==200){
					this.addressList = res.data
					this.defaultAdd = this.addressList.find(item => item.isDefault.key === 1)
					console.log(this.defaultAdd,'defaultAdd');
				}
				
			},
			async price(){
				var data = {
					itemAttrValueId:this.attrList.join(',')
				}
				const res = await attrValuePrice(data)
				if(res.code==200){
					this.total = res.data.price
				}
			
			},
			async buy() {
				console.log(111111);
				if (!this.dateValue) {
					uni.showToast({
						title: '请选择时间',
						icon: 'none'
					})
					return
				}
				if(this.car){
					var data = {
						"request": {
							"expectedServeStartTime": this.parseDateTimeRange(this.dateValue).startTimeFormatted,
							"expectedServeEndTime": this.parseDateTimeRange(this.dateValue).endTimeFormatted ,
							"userAddress": {
								"id": this.defaultAdd.id
							}
						},
						"comment": this.inputValue
					}
				}else{
					var data = {
						"request": {
							"expectedServeStartTime": this.parseDateTimeRange(this.dateValue).startTimeFormatted,
							"expectedServeEndTime": this.parseDateTimeRange(this.dateValue).endTimeFormatted ,
							"userAddress": {
								"id": this.defaultAdd.id
							}
						},
						"itemAttrValueId": this.attrList,
						"comment": this.inputValue
					}
				}
				
				if (!this.id) delete data.itemAttrValueId
				const res = await createOrder(data)
				if(res.code==200){
					var data = {
						orderNo: res.data.orderNo,
						payment: {
							payWay: 2,
						},
						paymentReq: {
							wayCode: 'WX_LITE'
						}
					}
					uni.redirectTo({
						url:`/pages-detail/pay/pay?data=${JSON.stringify(data)}&price=${this.total}&id=${res.data.id}`
					})
				}
				
			},
			async getShop() {
				const res = await ShopCar()
				if(res.code==200){
					this.list = res.rows
					console.log('this.list',this.list);
					this.list.forEach(item => {
						item.cart = item.cart.filter(i => i.isSelected.key === 1)
					})
				}
				
			},
			toDetail() {
				uni.$once('address', (item) => {
					this.defaultAdd = item
				})
				uni.navigateTo({
					url: '/pages-user/address/address?type=choose'
				})
			},
			async getDetail() {
				var data = {
					itemId: this.id
				}
				const res = await shopDetail(data)
				if(res.code==200){
					this.detail = res.data
					this.attr = this.detail.attrValueList.find(i => i.id == this.attrId)
					// this.total = this.attr.price
					this.price()
				}
				
			},
			generateTimeSlotsSimplified() {
				const now = new Date();
				const currentHour = now.getHours();
				const currentMinute = now.getMinutes();
				const roundedNow = this.roundToNextHour(new Date(now)); // 对当前时间进行舍四取五

				// 初始化时间段数组
				let timeSlots = [];

				// 从8点开始生成时间段，直到18点
				for (let hour = 8; hour < 18; hour++) {
					const startTime = new Date();
					startTime.setHours(hour, 0, 0, 0); // 设置小时为循环变量hour，分钟、秒、毫秒为0

					// 如果时间段的起始时间大于舍四取五后的当前时间，则添加到时间段数组中
					if (startTime >= roundedNow) {
						const endTime = new Date(startTime);
						endTime.setHours(startTime.getHours() + 1, 0, 0, 0); // 设置结束时间为起始时间的下一个小时

						// 格式化时间为字符串并添加到数组中
						const startString = startTime.toLocaleTimeString('zh-CN', {
							hour: '2-digit',
							minute: '2-digit'
						}).replace(/^\D*/, '');
						const endString = endTime.toLocaleTimeString('zh-CN', {
							hour: '2-digit',
							minute: '2-digit'
						}).replace(/^\D*/, '');
						timeSlots.push(`${startString}-${endString}`);
					}
				}
				this.nowTimeBox = timeSlots;
				this.timeBox = timeSlots
			},
			parseDateTimeRange(timeString) {
				// 解析中文日期字符串
				const dayMap = {
					'周日': 0,
					'周一': 1,
					'周二': 2,
					'周三': 3,
					'周四': 4,
					'周五': 5,
					'周六': 6
				};
				const [dayOfWeek, monthDayString, timeRange] = timeString.split(' ');
				const [month, day] = monthDayString.split('月').map(num => parseInt(num, 10));
				const [startTime, endTime] = timeRange.split('-');

				const currentYear = new Date().getFullYear();
				const date = new Date(currentYear, month - 1, day, ...startTime.split(':').map(num => parseInt(num, 10)));

				const targetDayOfWeek = dayMap[dayOfWeek];
				let offset = (targetDayOfWeek - date.getDay() + 7) % 7; 
				if (offset !== 0) {
					date.setDate(date.getDate() + offset); 
				}

				// 格式化开始时间和结束时间
				const formatDate = (dateObj, hoursOffset = 0) => {
					const year = dateObj.getFullYear();
					const month = String(dateObj.getMonth() + 1).padStart(2, '0');
					const day = String(dateObj.getDate()).padStart(2, '0');
					const hours = String(dateObj.getHours() + hoursOffset).padStart(2, '0');
					const minutes = String(dateObj.getMinutes()).padStart(2, '0');
					return `${year}-${month}-${day} ${hours}:${minutes}`;
				};

				const startTimeFormatted = formatDate(date);
				const endTimeFormatted = formatDate(new Date(date.getTime()), 1);

				return {
					startTimeFormatted,
					endTimeFormatted
				};
			},
			roundToNextHour(date) {
				const minutes = date.getMinutes();
				console.log(minutes);
				if (minutes >= 30) {
					// 如果分钟数大于或等于30，则向上取整到下一个小时
					date.setMinutes(0);
					date.setHours(date.getHours() + 1);
				} else {
					// 否则保持当前小时，分钟数设为0
					date.setMinutes(0);
				}
				return date;
			}
		},
		
	}
</script>

<style lang="scss" scoped>
	.backWindow{
		background-color: white;
		border-radius: 5px;
		padding: 20px;
		.title{
			font-weight: bold;
			text-align: center;
		}
		.content{
			font-size: 14px;
			color: $grey;
			margin: 10px 20px;
		}
		.button{
			font-size: 14px;
			background: $linerBlue;
			color:white;
			text-align: center;
			padding: 6px 0px;
			border-radius: 20px;
		}
		.tips{
			font-size: 14px;
			background: rgba(172, 212, 255, 0.2);
			color:$blue;
			text-align: center;
			padding: 6px 0px;
			border-radius: 20px;
			margin-top: 10px;
		}
	}
	
	.window {
		background-color: white;
		border-radius: 20px 20px 0 0;
		height: 50vh;
		z-index: 999;

		.icon {
			position: absolute;
			right: 20px;
			top: 22px;
			z-index: +1;
		}

		.title {
			font-weight: bold;
			text-align: center;
			padding: 20px;
		}

		.tips {
			background-color: #fdf6f0;
			color: #e08832;
			font-size: 14px;
			text-align: center;
			padding: 5px;
		}

		.button {
			background: $linerBlue;
			margin: 10px;
			text-align: center;
			padding: 10px 0px;
			color: white;
			border-radius: 50px;
		}



		.body {
			height: calc(50vh - 151px);
			display: flex;
			justify-content: space-between;
			align-items: flex-start;

			.left {
				height: 100%;
				width: 130px;
				white-space: nowrap;
				background-color: $MainBackColor;

				.item {
					display: flex;
					align-items: center;
					justify-content: center;
					padding: 20px 0px;
					font-size: 14px;
				}

				.act {
					background-color: white;
				}
			}

			.right {
				height: 100%;
				width: calc(100vw - 130px);

				.tip {
					width: calc(100% - 60px);
					height: calc(100% - 60px);
					display: flex;
					align-items: center;
					justify-content: center;
					padding: 30px;
					text-align: center;
					color: $grey;
				}

				.item {
					display: flex;
					align-items: center;
					padding: 20px;
					font-size: 14px;
				}

				.act {
					color: $blue;
				}
			}
		}
	}

	.BodyBox {
		margin: 20rpx;
		background-color: white;
		border-radius: 10px;
		margin-top: 0px;

		.totalBox {
			background-color: white;
			margin: 10px;
			padding: 10px;

			.title {
				font-weight: bold;
				font-size: 14px;
			}

			.couponBox {
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-size: 14px;
				margin: 5px 0px;
			}
		}

		.shopList {
			background-color: white;
			margin: 10px;
			padding: 10px;


			.item {
				background-color: white;

				border-radius: 5px;

				.cart {}

				.title {
					font-size: 14px;
				}

				.numBox {
					display: flex;
					align-items: center;
					margin-right: 10px;


					.num {
						font-size: 14px;
						background-color: $backGrey;
						width: 30px;
						height: 22px;
						display: flex;
						align-items: center;
						justify-content: center;
						border-radius: 5px;
					}
				}


				.formation {
					display: flex;

					.dot {
						width: 17px;
						height: 17px;
						border-radius: 50%;
						border: 1px solid $backGrey;
						margin: 0px 10px;
						margin-top: 30px;
						background-color: $backGrey;
					}

					.act {
						background-color: $blue;
						width: 100%;
						height: 100%;
						border-radius: 50%;
						display: flex;
						align-items: center;
						justify-content: center;

					}

					.img {
						width: 80px;
						height: 80px;
						margin: 10px 0px;
						margin-right: 10px;
						border-radius: 5px;
					}

					.form {
						display: flex;
						flex-direction: column;
						justify-content: space-between;
						margin: 10px 0px;
						width: calc(100% - 70px);

						.name {
							font-size: 14px;
						}

						.sku {
							font-size: 12px;
							color: $grey;
							margin-bottom: 10px;
						}

						.priceBox {
							width: 100%;
							display: flex;
							justify-content: space-between;
							align-items: flex-end;

							.price {
								font-size: 14px;
								font-weight: bold;

								.icon {
									font-size: 12px;
								}
							}

						}

					}

				}



				.delete {
					background-color: $red;
					border-radius: 20px;
					text-align: center;
					padding: 5px 15px;
					color: white;
					font-size: 12px;
				}

			}

		}

		.content {
			margin: 10px;
			background-color: white;
			padding: 10px;

			.title {
				font-weight: bold;
				font-size: 14px;
				margin-bottom: 10px;
			}
		}
	}

	.box {
		background-color: $MainBackColor;
		min-height: 100vh;
	}


	.buttonBox {
		background: white;
		position: fixed;
		z-index: 88;
		bottom: 0px;
		width: 750rpx;
		height: 150rpx;
		padding:  0 20rpx;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.button {
			background: $linerBlue;
			color: white;
			padding: 10px 65px;
			border-radius: 50px;
		}

		.price {
			font-size: 20px;
			font-weight: bold;
			color: $red;

			.icon {
				font-size: 14px;
			}
		}
	}

	.addressList {
		width:710rpx;margin:0 auto;
		margin-top: 10rpx;margin-bottom: 10rpx;

		.time {
			background-color: white;
			border-radius: 0 0 10px 10px;
			padding: 10px;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding-bottom: 20px;

			.title {
				font-size: 14px;
				font-weight: bold;
				display: flex;
				align-items: center;
			}

			.timeBox {
				display: flex;
				align-items: center;

				.value {
					color: $grey;
					font-size: 12px;
					margin-right: 5px;
				}
			}
		}

		.top {
			display: flex;
			align-items: center;
			justify-content: space-between;
			background: $linerBlue;
			padding: 10px 20px;
			border-radius: 10px 10px 0 0;

			.text {
				font-weight: bold;
				font-family: '服务保障';
				font-size: 12px;
				color: white;
			}

			.tips {
				font-size: 12px;
				color: white;
			}
		}

		.item {
			background-color: white;
			padding: 10px;

			.where {
				font-size: 14px;
				margin-left: 5px;
			}

			.name {
				font-size: 12px;
				color: $grey;
			}

			.detail {
				font-weight: bold;
				font-size: 14px;
				margin: 5px 0px;
			}
		}
	}
</style>